<?php

/**
 * bearychat.php
 *
 * @copyright  2017 opencart.cn - All Rights Reserved
 * @link       http://www.guangdawangluo.com
 * @author     Edward Yang <yangjin@opencart.cn>
 * @created    2017-06-22 11:17
 * @modified   2017-06-22 11:17
 */
class BearyChat
{
    private $hook = '';
    private $client = null;
    private $registry = null;
    public static $bhInstance = null;

    public function __construct($registry, $hook = null)
    {
        if ($hook) {
            $this->hook = $hook;
        } else {
            $this->hook = 'https://hook.bearychat.com/=' . BEARYCHAT_HOOK;
        }
        $this->registry = $registry;
        if (class_exists(\ElfSundae\BearyChat\Client::class)) {
            $this->client = new \ElfSundae\BearyChat\Client($this->hook);
        }
    }

    public function __get($key)
    {
        return $this->registry->get($key);
    }

    public function __set($key, $value)
    {
        $this->registry->set($key, $value);
    }

    public static function getInstance($registry, $hook = null)
    {
        if (!self::$bhInstance) {
            self::$bhInstance = new self($registry, $hook);
        }
        return self::$bhInstance;
    }

    public function send($text)
    {
        if (!$this->client) {
            return;
        }
        $message = $text . "\n";
        $message .= $this->getUser();
        $this->client->sendMessage(array(
            'text' => $message
        ));
    }

    public function getUser()
    {
        $userMessage = "IP: " . \Guangda\Ip_Utils::get() . "\n";
        $userMessage .= "User Agent: " . $_SERVER['HTTP_USER_AGENT'] . "\n";
        $userMessage .= "Request: " . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'] . "\n";
        if ($this->customer && $this->customer->isLogged()) {
            $userMessage .= 'Customer ID: ' . $this->customer->getId() . "\n";
            $userMessage .= 'Customer Name: ' . $this->customer->getFirstName() . "\n";
            $userMessage .= 'Customer Email: ' . $this->customer->getEmail() . "\n";
            $userMessage .= 'Customer Tel: ' . $this->customer->getTelephone() . "\n";
        }
        if ($this->user && $this->user->isLogged()) {
            $userMessage .= 'Admin ID: ' . $this->user->getId() . "\n";
            $userMessage .= 'Admin Name: ' . $this->user->getUserName() . "\n";
        }
        return $userMessage;
    }
}